var service = new EbeimService();
var service2 = new EbeimService2();
var $pagesize = 14;
var $pageNo = 1;
var isSelf="1";
var $dsName='';
var $dsId='';

//init
$(function(){
	
	$("#w-page").keyup(function(){
		if(event.keyCode == 13){
			var flag = $("#w-page").val();
			page(flag);
		}
	});
	
	if(plugin.GetQueryString("isSelf")==0)
	{
		$("#otherTerminal")[0].checked=true;
	}
	otherTerminlalCheck();
	var dsType = getParameter("dsType");
	$dsName = getParameter("dsName");
	$("#h_dsType").val(dsType);
	if(dsType != "0" && dsType != "1" && dsType != "2"){
		plugin.msgtip({type: "o", msg: "参数缺失！"});
//		window.history.go(-1);
	}
	getDateSoucesByPage();
	setInterval("getUploadProcessBar()", 2500);
	setInterval("getDateSoucesByPage()", 300000);
	
//	setInterval("getUploadProcessBarAll()", 2500);
	
	$("#otherTerminal").change(function(){
		otherTerminlalCheck();
		getDateSoucesByPage();
	});
});

function showUploadBar(){
	showDialog('uploadWindow');
}
function deleteUploadBar(dsId){
	if(!dsId){
		dsId = "";
		$(".delUploadBtn").each(function(){
			dsId += $(this).attr("id")+",";
		});
		if(dsId.length>0){
			dsId = dsId.substring(0,dsId.length-1);
		}
	}
	if(!dsId || dsId.length==0){
		plugin.msgtip({type:"e",msg:"还没可以清除的数据!"});
		return;
	}
	service.deleteUploadProcessBar(
		{
			dsIds:dsId
		},
		function(data){
			$(".j-delete").css("display","none");
			$(".j-undelete").css("display","inline-block");
		}
	);
}
function getUploadProcessBarAll(data){
//	service.getUploadProcessBarAll({
//		dsType:0
//	}, function(data){
		var beans = data.beans;
		var uploadProcessbarContent = "";
		var jtag = $("#upload_process_tag").siblings(".j-tag");
		if(beans.length > 0){
			$("#upload_process_tag").css("display","block");
			$("#upload_process_tag").html(beans.length);
			jtag.css("display","block");
			jtag.html(beans.length);
			jtag.stop();
			jtag.animate({padding:"8px",top:"-10px",right:"-5px",opacity:"0"},500,function(){
				$(this).css({padding:"3px",top:"-5px",right:"0",display:"none",opacity:"1"});
			})
		}else{
			$("#upload_process_tag").css("display","none");
		}
	//	for(var i = 0; i<beans.length; i++){
		for(var i=beans.length-1; i>=0; i--){
			var bean = beans[i];
			var fs = bean.fileSum - (bean.okSum + bean.errorSum);
			//var p = (bean.count * 100 / bean.total).toFixed(2);
			var p = (Math.floor((bean.count * 100 / bean.total)*100)/100).toFixed(2);
			if(bean.total==0){
				p = 100;
			}
			var info = "";
			var btn = "";
			if(p == 0 && fs>0){
				info="上传队列中<img src='/web/images/loading.gif' style='margin-bottom: -3px; margin-left: 3px;'>"
			}else if(bean.errorSum>=bean.fileSum){
				info="<span style='color:red'>上传失败!</span>"
				$(".j-delete").css("display","inline-block");
				$(".j-undelete").css("display","none");
			}else if(p >= 100 || fs<=0){
				if(bean.status==1){
					info = "文件校验中<img src='/web/images/loading.gif' style='margin-bottom: -3px; margin-left: 3px;'>";
				}else{
					info = "上传完成!";
				}
				p = 100;
				btn = "<a class='delUploadBtn' id='"+bean.dsId+"' href='javascript:deleteUploadBar(\""+bean.dsId+"\");'>删除</a>";
				$(".j-delete").css("display","inline-block");
				$(".j-undelete").css("display","none");
			}else{
				info = "上传进度:"+ p + "%";
			}
			uploadProcessbarContent = uploadProcessbarContent
			+"<tr>"
			+"	<td><nobr title='"+bean.name+"' style='max-width:200px;display:inline-block;overflow:hidden;text-overflow:ellipsis;'>"+bean.name+"</nobr></td>"
			+"	<td width='150px' style='font-size:12px;text-align:center;'>"+getTimeStr(bean.createtime)+"</td>"
			+"	<td width='150px' style='text-align:center;' dsid='"+bean.id+"' class='processTD'>"
			
			+"<div class='processbar' style='background:#999;width:100px;height:20px;position:relative;margin:0 auto;'>"
			+ "<div class='bar' style='height:20px;background:green;width:"+p+"%;'></div>"
			+ "<div class='info' style='font-size:12px;width:100px;height:20px;color:#fff;position:absolute;top:0;left:0'>"
			+	info
			+" </div>"
			+"</div>"
			
			+"</td>"
			+"	<td width='60px;' style='text-align:center;'>"+btn+"</td>"
			+"</tr>";
		}
		$("#uploadProcessbarTB").html(uploadProcessbarContent);
//	});
}

var dsCB = function(data){
	var content = "";
	for(var i=0;i<data.length;i++){
		var obj = data[i];
		console.log(obj);
		var dsStatus = obj.dsStatus;
		var statusBtn = "<font color='red'>禁用</font>";
		if(dsStatus == "1"){
			dsStatus = 0;
			statusBtn = "<font color='green'>启用</font>";
		}else{
			dsStatus = 1;
		}
		
		var backupBtnFunc = "onclick='javascript:handBackup(\"" + obj.dsId + "\","+ obj.dsSecurityRank + ")'";
		var backupClass='opr-btn';
		var jedit = " <button class='opr-btn' type='button' onclick='toPage(\"/static/html/web_data_form.html?dsType="+$("#h_dsType").val()+"&dsId="+obj.dsId+"\")'>编辑</button>"
		if(data.terminalId != obj.terminalId){
			backupClass='grey-opr-btn';
			backupBtnFunc="";
			jedit = " <button class='"+backupClass+"' type='button'>编辑</button>";
		}

		var version=obj.currentVersionMajor
		if(obj.status==1)
		{
			version=parseInt(version)-1;
		}
		content = content
		+"<tr>"
		+"	<td><input dsrank='"+ obj.dsSecurityRank + "' type='checkbox' name='ck' value="+obj.id+"></td>"
		+"	<td>"+(i+1)+"</td>"
		/*+"	<td><input class='inp-name' type='text' value='"+obj.name+"' readonly='readonly' style='width:134px'></td>"*/
		+"	<td><span title='"+obj.name+"'>"+obj.absPath+"</span></td>"
		+"	<td>"+111+"</td>"
		+"	<td>"+getTimeStr(obj.createTime)+"</td>"
		+"	<td>"+translateStatus(obj.dsStatus,obj.status,obj.id,obj.description)+"</td>"
		+"	<td class='' dsStatus='"+obj.dsStatus+"'>"
		+"		<button class='opr-btn' type='button' id='statusBtn"+obj.id+"' onclick='javascript:changeDsStatus("+dsStatus+",\"" + obj.id + "\","+ obj.dsSecurityRank + ")'>"+statusBtn+"</button>"
		+jedit
		//+"		<button class='opr-btn' type='button' id='backupBtn"+obj.id+"' onclick='javascript:"+backupBtnFunc+"'>备份</button>"
		+"		<button class='"+backupClass+"' type='button' id='backupBtn"+obj.id+"' "+backupBtnFunc+">备份</button>"
		+"		<button class='opr-btn' type='button' onclick='toPage(\"/static/download2.html?dsType="+$("#h_dsType").val()+"&dsId="+obj.dsId+"&isSelf="+isSelf+"&terminalId="+obj.terminalId+"&version="+version+".0"+"&status="+obj.status+"&path="+"/"+"\")'>列表</button>"
		+"	</td>"
		+"</tr>";
	}
	if(data.length>0){
		$("#tbody").html(content);
	}else{
		$("#tbody").html("<tr><td colspan='7' style='text-align:center;'>暂无数据</td></tr>");
	}
	gennerPage(data.page.totalPage,data.page.totalRecord);
	getUploadProcessBar();
	countByType($uploadFailed);
}
function setDynamicCode() {
	var dynamicCode = $("#dynamicCode").val().replace(/(^\s+)|(\s+$)/g,"");
	if (dynamicCode == "") {
		plugin.msgtip({type: "e", msg: "动态验证码不能为空!"});
		return;
	}
	var dsId = $("#h_dsId").val();
	var dsSecurityRank = $("#h_dsSecurityRank").val();
	var whichGetModel = $("#h_whichGetModel").val();
	if (whichGetModel == "handBackup") {
		handBackup(dsId, dsSecurityRank, dynamicCode)
	} else if (whichGetModel == "changeDsStatus") {
		var dsStatus = $("#h_dsStatus").val();
		changeDsStatus(dsStatus, dsId, dsSecurityRank, dynamicCode)
	} else if (whichGetModel == "changeDsStatusMany") {
		var dsStatus = $("#h_dsStatus").val();
		changeDsStatusMany(dsStatus,dynamicCode);
	}
}
var handBackupCB = function(data) {
	var dsid = $("#h_dsId").val();
	$("#backupBtn"+dsid).removeAttr("disabled");
	var json = data;
	if (json.code == "200" || json.code == 200) {
		plugin.msgtip({type: "o", msg: "成功加入备份队列!"});
		closeCodeWindow();
		$("#dynamicCode").val("");
	} else {
		dsSecurityRankCheck(json,json.message);
	}

}
function handBackup(dsId, dsSecurityRank, dynamicCode) {
	var currentDsStatus = $("#statusBtn"+dsId).parent().attr("dsStatus");
	if(currentDsStatus=="1"){
		plugin.msgtip({type:"e",msg:"该数据源已被禁用!"});
		return;
	}
	$("#h_whichGetModel").val("handBackup");
	$("#h_dsId").val(dsId);
	$("#h_dsSecurityRank").val(dsSecurityRank);
	$("#backupBtn"+dsId).attr("disabled","disabled");
	service.backup(
			{
				dsId:dsId,
				dsSecurityRank:dsSecurityRank,
				dynamicCode:dynamicCode
			},
			handBackupCB
	);
}
//数据源列表
function getDateSoucesByPage(){
//	var pageNo = getParameter('pno');
//	if(pageNo==undefined||pageNo==""){
//		pageNo = 0;
//	}
	var $motor_dsId = '';
	 $motor_dsId = getParameter("dsId");
	service.getDataSourcesByPage({
		offset:$pageNo,
		pagesize:$pagesize,
		dsType:$("#h_dsType").val(),
		dsStatus:"",
		name:$dsName,
		dsId:$motor_dsId,
		isSelf:isSelf
	}, dsCB);
}

//启用禁用
function changeDsStatusMany(flag,dynamicCode){
	var ids = getCkValue("ck");
	var dsSecurityRank = 0;
	$("input[name='ck']:checked").each(function(){
		var v = $(this).attr("dsrank");
		if(parseInt(v)>dsSecurityRank)
		{
			dsSecurityRank=v;
		}
//		if(v=="1" && dsSecurityRank !=2){
//			dsSecurityRank  = 2;
//		}
//		if(v=="2"){
//			dsSecurityRank  = 2;
//		}
	});
	if(ids.length==0){
		plugin.msgtip({type:"e",msg:"请至少选择一项进行操作!"});
		return;
	}
	$("#h_dsStatus").val(flag);
	$("#h_whichGetModel").val("changeDsStatusMany");
	service.updataStatusMany({
		ids:ids,
		dsStatus:flag,
		dsSecurityRank:dsSecurityRank,
		dynamicCode:dynamicCode,
	},
	function(data){
		if(data.code=="200"){
			$("#ckall")[0].checked = false;
			closeCodeWindow();
			getDateSoucesByPage();
		}else if(data.code=="500"){
			plugin.msgtip({type:"e",msg:data.message});
			return;
		}else{
			closeCodeWindow();
			dsSecurityRankCheck(data);
		}
	});
}
function changeDsStatus(dsStatus, dsId, dsSecurityRank, dynamicCode) {
	$("#h_dsId").val(dsId);
	$("#h_dsSecurityRank").val(dsSecurityRank);
	$("#h_dsStatus").val(dsStatus);
	$("#h_whichGetModel").val("changeDsStatus");
	var ds = {
		id : dsId,
		dsStatus : dsStatus,
		dsSecurityRank : dsSecurityRank,
		dynamicCode : dynamicCode
	};
	$("#statusBtn"+dsId).attr("disabled","disabled");
	$dsId = dsId;
	var json = {};
	json["datasource"] = ds;
	service.addDataSource(json, changStatusCB);
}
var changStatusCB = function(data) {
	$("#statusBtn"+$dsId).removeAttr("disabled");
	var json = data;
	if (json.code == "200") {
		plugin.msgtip({type: "o", msg: "操作成功"});
		closeCodeWindow();
		$("#dynamicCode").val("");
		getDateSoucesByPage();
	} else {
		dsSecurityRankCheck(json,json.message);
	}
}

function translateStatus(dsStatus,status, dsId,description) {
	var color = "green";
	if(dsStatus==1){
		status = "禁用";
		color = "red";
	}
	else if (status == 0) {
		status = "等待备份";
	} else if (status == 1) {
		status = "备份中<img src='/web/images/loading.gif' style='margin-bottom: -3px; margin-left: 3px;'>";
		if(description){
			status = description+"<img src='/web/images/loading.gif' style='margin-bottom: -3px; margin-left: 3px;'>";
		}
	} else if (status == 2) {
		status = "备份失败";
		if(description){
			status = "备份失败["+description+"]";
		}
		color = "red";
	} else if (status == 3) {
		status = "备份完成，等待下次备份";
	}
	var str = "<div class='processbar' dsid='"
		+ dsId
		+ "' style='background:#ddd;width:150px;height:20px;position:relative;margin:0 auto;'>"
		+ "<div class='bar' style='height:20px;'></div>"
		+ "<div class='info' style='font-size:12px;width:150px;height:20px;line-height:20px;color:"+color+";position:absolute;top:0;left:0'>"+status+"</div>"
		+ "</div>";
	return str;
}

function otherTerminlalCheck(){
	if($("#otherTerminal")[0].checked){
		isSelf="0";
	}else{
		isSelf="1";
	}
}

var uploadPrcessBarCB = function(data) {
	getUploadProcessBarAll(data);
	var list = data.beans;
	for (var i = 0; i < list.length; i++) {
		var bean = list[i];
		var fileSum = bean.fileSum;
		var okSum = bean.okSum;
		var errorSum = bean.errorSum;
		$(".processbar").each(
			function() {
				var dsid = $(this).attr("dsid");
				if (dsid == bean.dsId) {
					$(this).css("border", "solid 1px green");
					$(this).find(".bar").css("background", "green");
					$(this).find(".info").css("color", "#fff")
					if (bean.count >= bean.total || okSum+errorSum>=fileSum) {
						$(this).find(".bar").css("width", 100 + "%");
						$(this).find(".info").html("100.00%");
						$(this).css("border", "0");
						$(this).find(".bar").css("width", 0);
						$(this).find(".info").css("color", "green")
						$(this).find(".info").html("文件校验中<img src='/web/images/loading.gif' style='margin-bottom: -3px; margin-left: 3px;'>");
					} else {
						var p = Math.floor((bean.count * 100 / bean.total)*100)/100;
						//var p = (bean.count * 100 / bean.total).toFixed(2);
						$(this).find(".bar").css("width",p+ "%");
						if(p == 0 && errorSum==0){
							$(this).find(".info").html("上传队列中<img src='/web/images/loading.gif' style='margin-bottom: -3px; margin-left: 3px;'>");
						}else if(p == 0 && errorSum==fileSum){
							$(this).find(".info").html("<span style='color:red'>上传失败!</span>");
						}else{
							$(this).find(".info").html(p+ "%");
						}
					}

				}
			});
	}
}
function getUploadProcessBar() {
	var ids = "";
	$(".processbar").each(function() {
		ids += $(this).attr("dsid") + ",";
	});
	if (ids.length > 0) {
		ids = ids.substring(0, ids.length - 1);
		
		service.getUploadProcessBar(
			{
				dsIds:ids
			}, 
			uploadPrcessBarCB
		);
		
		service.deleteUploadProcessBar(
			{
				dsIds:ids
			},
			delProcessbarCB,
			function(data){
//				window.location.href = "/static/html/login.html";
			}
		);
	}
}

var delProcessbarCB = function(data) {
	if(data.code=="200"){
//		window.location.reload();
		getDateSoucesByPage();
	}
}

//分页控件
function gennerPage(totalPage,totalRecords){
	if(totalPage==0){
		totalPage = 1;
	}
    //分页参数，有些参数是可选的，比如lang，若不传有默认值
    var pageData = {
        pno : $pageNo,
        //总页码
        total : totalPage,
        //总数据条数
        totalRecords : totalRecords,
	    mode : 'click',//默认值是link，可选link或者click
	    click : function(n){
	    	if(!n){
	    		n = 1;
	    	}
	    	$pageNo = n;
	    	otherTerminlalCheck();
    		service.getDataSourcesByPage({
				offset:n,
				pagesize:$pagesize,
				dsType:$("#h_dsType").val(),
				dsStatus:"",
				name:$dsName,
				dsId:"",
				isSelf:isSelf
			}, dsCB);
	    }
    	}
    //初始化分页
    kkpager.init(pageData);
    //生成分页
    //有些参数是可选的，比如lang，若不传有默认值
    kkpager.generPageHtml(pageData);
}
//全选
function checkAll(spId,ckName){
	if($("#"+spId)[0].checked){
		$("input[name='"+ckName+"']").each(function(){
			$(this)[0].checked = true;
		});
	}else{
		$("input[name='"+ckName+"']").each(function(){
			$(this)[0].checked = false;
		});
	}
}
//获取选择的值
function getCkValue(ckName){
	var rs = "";
	$("input[name='"+ckName+"']").each(function(){
		if($(this)[0].checked){
			rs = rs + $(this).attr("value") + ","
		}
	});
	if(rs.length > 0){
		rs = rs.substring(0,rs.length-1);
	}
	return rs;
}
//
function goToclientFolder(version){
	if (version == "") {
		plugin.msgtip({type: "e", msg: "您当前没有版本可以下载!"});
		return;
	}
}
